package com.example.imtoken.modules.main

import android.view.KeyEvent
import com.blankj.utilcode.util.*
import com.example.imtoken.R
import com.example.imtoken.core.base.BaseActivity
import com.example.imtoken.core.utils.BusConfig
import com.example.imtoken.databinding.ActivityMainBinding
import kotlin.system.exitProcess

class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>(MainViewModel::class.java) {

    private lateinit var AccessRequest: Array<String>

    override fun initLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun init() {
        ActivityUtils.finishAllActivitiesExceptNewest()
        BusUtils.register(this)
        getPermission()
    }

    @BusUtils.Bus(tag = BusConfig.page_index_sticky_main_activity, sticky = true)
    fun pageInitBar(page: Int) {
        when (page) {
            0 -> initBar(true, R.color.barBomColor)
            1 -> initBar(false, R.color.xui_config_color_transparent)
            2 -> initBar(true, R.color.barBomColor)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        BusUtils.removeSticky(BusConfig.page_index_sticky_main_activity)
        BusUtils.unregister(this)
    }

    /**
     * 权限申请
     */
    private fun getPermission() {
        val permissionList = PermissionUtils.getPermissions()
        val sb = StringBuffer()
        for (permission in permissionList) {
            sb.append("\n").append(permission)
        }
        LogUtils.e("初始化权限申请", sb.toString())
        AccessRequest = permissionList.toTypedArray()
        PermissionUtils.permission(*AccessRequest)
            .callback(object : PermissionUtils.SimpleCallback {
                override fun onGranted() {

                }

                override fun onDenied() {

                }

            }).request()
    }

    private var exitTime = 0L
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event?.action == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtils.showShort("再按一次退出程序")
                exitTime = System.currentTimeMillis()
            } else {
                finish()
                exitProcess(0)
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

}